package cn.admin.hessian.io;

import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class JavaDeserializationBridge {

    private static Field f_cons;

    public static Object newInstance(Class<?> type) throws InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        if (!Serializable.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException(type + " not serializable.");
        } else {
            ObjectStreamClass osc = ObjectStreamClass.lookup(type);
            Constructor<?> constructor = (Constructor)f_cons.get(osc);
            return constructor.newInstance();
        }
    }

    static {
        try {
            f_cons = ObjectStreamClass.class.getDeclaredField("cons");
            f_cons.setAccessible(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
